package com.hssoftvn.android.apps.tinycouplechat;

import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.text.format.DateFormat;

//http://stackoverflow.com/questions/4300291/example-communication-between-activity-and-service-using-messaging
//http://www.vogella.com/tutorials/AndroidServices/article.html

public class ServiceCheckingIncomingMSG extends Service {

	Timer timer;
	final int UPDATE_TIME = 500;
	class MessageCheckerTimer extends TimerTask
	{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try{					
				int i=0;
				//Thread.sleep(10);
				//Utils.ShowToast("Start TimerTask");
				i++;
				String responses = NetworkHelper.getHttpResponse(NetworkHelper.URL_CHECKING_INCOMING_MSG);
    			//e|errorCode|f|FROM|m|MESSAGE|d|DATE SENT
    			String[] temp = responses.replace('|', '~').split("~");
    			//String errorCode=temp[1];
    			//String from=temp[3];
    			String message="Tiny";
    			//String datesent=temp[7];
    			ChatItem item = new ChatItem("", "", Utils.TYPE_YOU);
    			item.setText(message + ".." + DateFormat.format("dd-MM-yy hh:mm:ss", System.currentTimeMillis()));
    			sendBroadcastMessage(Utils.INTENT_MSG_RECEIVED,item);
			}catch(Exception e){
					Utils.ShowToast(e.getMessage());
					e.printStackTrace();
			}						
		}
	}
	
	@Override
		public void onCreate() {
			// TODO Auto-generated method stub			
			super.onCreate();
			timer = new Timer();
			Utils.ShowToast("Service:onCreate!!");
		}
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    //TODO do something useful    
	  Utils.ShowToast("Service:onStartCommand!!");
    //to run a thread here to check incoming msg		
		timer.schedule(new MessageCheckerTimer(), UPDATE_TIME, UPDATE_TIME);

	  return Service.START_STICKY;
  }

  @Override
  public IBinder onBind(Intent intent) {
  //TODO for communication return IBinder implementation
    return null;
  }  
  
  public void sendBroadcastMessage(String intentFilterName, ChatItem extra) {
      Intent intent = new Intent(intentFilterName);
      
      intent.putExtra(Utils.EXTRA_INCOMING_MSG, extra.getText());
      
      sendBroadcast(intent);
  }
  
} 